using System;
using System.Text.RegularExpressions;
using System.Web;
using System.ComponentModel;
using System.Web.UI;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Text;

namespace com.flajaxian
{
    /// <summary>
    /// 
    /// </summary>
    [ToolboxItem(false), AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal), AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    [ParseChildren(false)]
    public class FileUploaderTemplateItem : Control, INamingContainer
    {
        private FileUploader _parent;
        private string _name;
        private string _text = null;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="name"></param>
        public FileUploaderTemplateItem(FileUploader parent, string name)
        {
            this._parent = parent;
            this._name = name;
        }
        /// <summary>
        /// 
        /// </summary>
        public FileUploader Parent { get { return this._parent; } }
        /// <summary>
        /// 
        /// </summary>
        public string Name { get { return this._name; } }

        /// <summary>
        /// 
        /// </summary>
        public string Text
        {
            get
            {
                if (this._text == null)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (Control control in this.Controls)
                    {
                        LiteralControl lc = control as LiteralControl;
                        if (lc != null)
                        {
                            sb.Append(lc.Text);
                        }
                    }
                    this._text = sb.ToString().Trim();
                    // strip SCRIPT tags but only from script templates
                    if (this.Name != "html" && Regex.IsMatch(this._text, Constants.Regex_StripScriptTags))
                    {
                        this._text = Regex.Replace(sb.ToString(), Constants.Regex_StripScriptTags, String.Empty, RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline);
                    }
                    if (this._text.IndexOf(Constants.CdataBeginning) == 0)
                    {
                        sb = new StringBuilder(this._text);
                        sb.Replace(Constants.CdataBeginning, String.Empty, 0, Constants.CdataBeginning.Length);
                        sb.Replace(Constants.CdataEnd, String.Empty, sb.Length - Constants.CdataEnd.Length - 1, Constants.CdataEnd.Length + 1);
                        this._text = sb.ToString();
                    }
                }
                return this._text;
            }
        }
    }
}
